import { add_edit_role, role_info } from '@/services/role';
import authList from '@/utils/auth';
import { ActionType, ProForm, ProFormGroup, ProFormText } from '@ant-design/pro-components';
import { useModel } from '@umijs/max';
import { Divider, Form, message, Modal, Spin, Switch, Tree } from 'antd';
import { useEffect, useState } from 'react';
interface Iprops {
  isShowEditRoleModal: (show: boolean) => void;
  isEditRoleModalOpen: boolean;
  actionRef: React.MutableRefObject<ActionType | undefined>;
  editId: number | undefined;
  flag: string;
}
type Info =
  | {
    auth: string;
    create_time: string;
    id: number;
    is_delete: number;
    manage_id: number;
    platform_id: number;
    remark: string;
    rolename: string;
    status: number;
    update_time: string;
  }
  | undefined;
type Val = {
  rolename: string;
  status: number;
  remark: string;
};
const EditRolePermission = (props: Iprops) => {
  const { initialState, setInitialState } = useModel('@@initialState');

  const { isEditRoleModalOpen, isShowEditRoleModal, actionRef, editId, flag } = props;
  // 存储角色详情
  const [roledata, setroledata] = useState<any>(undefined);
  // 存储权限列表
  const [auth, setauth] = useState<any>(undefined);
  // 存储选中的权限
  const [selectedAuth, setselectedAuth] = useState([]);
  // 选中某个权限的回调
  const onCheck = (checkedKeys: any, info: any) => {
    let auth = checkedKeys
    let newAuthList: any = []
    authList.map(((item: any) => {
      if (item.children) {
        newAuthList.push(item.id)
      }
    }))
    console.log('newAuthList', newAuthList);
    let filteredArray = auth.filter((item: any) => !newAuthList.includes(item));
    console.log('flbhnszgfjh', filteredArray);
    setselectedAuth(filteredArray);
  };
  // 组件初始化渲染 获取角色详情以及权限列表
  useEffect(() => {
    const getData = async () => {
      if (editId) {
        let request_body = {
          id: editId,
        };
        let params: any = await role_info(request_body);
        console.log('角色详情', params);
        if (params.msg == 'ok') {
          //设置用户详情
          let auth = JSON.parse(params.data.auth)
          let newAuthList: any = []
          authList.map(((item: any) => {
            if (item.children) {
              newAuthList.push(item.id)
            }
          }))
          console.log('newAuthList', newAuthList);
          let filteredArray = auth.filter((item: any) => !newAuthList.includes(item));
          console.log('flbhnszgfjh', filteredArray);
          setselectedAuth(filteredArray);
          setroledata(params.data);
        }
      }
    };
    get_auth_list();
    getData();
  }, []);

  // 获取权限列表
  const get_auth_list = async () => {
    let arr = initialState?.currentUser?.current_platform.model_permissions;
    console.log('arr', arr);
    let newArr: any = [];
    authList.map((item: any) => {
      if (arr.some((i: any) => i == item.id)) {
        newArr.push(item);
      }
    });
    if (newArr.length > 0) {
      newArr.map((item: any) => {
        item.key = item.id;
        item.children?.map((item2: any) => {
          item2.key = item2.id;
        });
      });
      setauth(newArr);
    }
  };
  // 编辑角色
  const edit_role = async (value: Val) => {
    console.log(value, value);
    if ('status' in value) {
      var switch_status = value.status ? 1 : 0;
    } else {
      var switch_status: number = roledata.status;
    }
    //组织数据
    let request_body = {
      id: editId,
      rolename: value.rolename,
      status: switch_status,
      remark: value.remark,
      auth_ids: JSON.stringify(selectedAuth),
    };
    //提交
    let res: any = await add_edit_role(request_body);
    console.log('res', res);
    if (res.msg == 'ok') {
      //刷新列表
      actionRef.current?.reload();
      message.success('添加成功');
      //关闭弹窗
      isShowEditRoleModal(false);
    } else {
      message.error(res.msg);
    }
  };
  return (
    <Modal
      title={flag == 'check' ? '查看权限' : '编辑权限'}
      centered
      open={isEditRoleModalOpen}
      onCancel={() => isShowEditRoleModal(false)}
      width={700}
      destroyOnClose={true}
      footer={null}
    >
      <Divider />
      {auth === undefined || roledata === undefined ? (
        <div
          style={{
            margin: '20px 0',
            marginBottom: '20px',
            padding: '30px 50px',
            textAlign: 'center',
          }}
        >
          <Spin size="large" />
        </div>
      ) : (
        <ProForm<{
          rolename: string;
          status: number;
          remark: string;
        }>
          onReset={() => isShowEditRoleModal(false)}
          onFinish={(value) => edit_role(value)}
          submitter={{
            searchConfig: {
              submitText: '提交',
              resetText: '返回',
            },
            resetButtonProps: {
              style: {
                // 隐藏重置按钮
                display: flag == 'edit' ? 'block' : 'none',
                position: 'absolute',
                left: 'calc(50% - 107px)',
              },
            },
            submitButtonProps: {
              style: {
                display: flag == 'edit' ? 'block' : 'none',
                position: 'absolute',
                right: 'calc(50% - 107px)',
              },
            },
          }}
        >
          <div style={{ display: 'flex' }}>
            <div style={{ flex: '1' }}>
              <ProFormGroup>
                <ProFormText
                  disabled={flag == 'check' ? true : false}
                  width={250}
                  name="rolename"
                  label="角色名称"
                  placeholder="请输入角色名称"
                  initialValue={roledata.rolename}
                  rules={[
                    {
                      required: true,
                      message: '请输入角色名称',
                      validateTrigger: 'onBlur',
                    },
                    { pattern: /(^\S)((.)*\S)?(\S*$)/, message: '不能输入空格' },
                  ]}
                />
                <Form.Item name="status" label="状态" valuePropName="checked">
                  <Switch
                    checkedChildren="启用"
                    unCheckedChildren="禁用"
                    key={roledata.status === 1}
                    defaultChecked={roledata.status === 1}
                    disabled={flag == 'check' ? true : false}
                  />
                </Form.Item>
                <ProFormText
                  width={340}
                  name="remark"
                  label="备注"
                  placeholder="请输入备注信息"
                  initialValue={roledata.remark}
                  disabled={flag == 'check' ? true : false}
                />
              </ProFormGroup>
            </div>
            <div style={{ flex: '1', marginLeft: '30px' }}>
              <Form.Item name="auth" label="权限" valuePropName="checked">
                {auth === undefined ? (
                  <div
                    style={{
                      margin: '20px 0',
                      marginBottom: '20px',
                      padding: '30px 50px',
                      textAlign: 'center',
                    }}
                  >
                    <Spin size="large" />
                  </div>
                ) : (
                  <Tree
                    checkable
                    // checkable 状态下节点选择完全受控（父子节点选中状态不再关联
                    // checkStrictly={true}
                    defaultExpandAll={true}
                    defaultCheckedKeys={selectedAuth}
                    selectable={false}
                    onCheck={onCheck}
                    treeData={auth}
                    disabled={flag == 'check' ? true : false}
                  />
                )}
              </Form.Item>
            </div>
          </div>
          <br />
        </ProForm>
      )}
      <br />
    </Modal>
  );
};
export default EditRolePermission;
